<?php
session_start(); // 开启会话

// 连接数据库
$servername = "localhost";
$mysqluser = "root";
$dbpass = "mysql123456";
$dbname = "student";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $mysqluser, $dbpass, array(
        PDO::ATTR_PERSISTENT => true
    ));
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (isset($_POST['homecomment'])) {
            // 处理插入评论请求
            // 获取表单数据
            if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
                throw new Exception('用户未登录');
            }
            $user_id = $_SESSION['user_id'];
            $username = $_SESSION['username'];
            $homecomment = $_POST['homecomment'];

            // 插入数据到 comments 表
            $stmt = $conn->prepare("INSERT INTO comments (id, name, homecomment) VALUES (:user_id, :username, :homecomment)");
            $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $stmt->bindParam(':username', $username, PDO::PARAM_STR);
            $stmt->bindParam(':homecomment', $homecomment, PDO::PARAM_STR);
            $stmt->execute();

            echo '评论提交成功';
        }
    } elseif ($_SERVER["REQUEST_METHOD"] == "GET") {
        // 处理查询评论请求
        // 查询 comments 表
        $stmt = $conn->prepare("SELECT id, name, homecomment FROM comments");
        $stmt->execute();
        $comments = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 返回 JSON 格式的结果
        header('Content-Type: application/json');
        echo json_encode($comments);
    }
} catch (PDOException $e) {
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        echo '数据库操作失败: ' . $e->getMessage();
    } elseif ($_SERVER["REQUEST_METHOD"] == "GET") {
        http_response_code(500);
        echo json_encode(array('error' => '数据库查询失败: ' . $e->getMessage()));
    }
}
?>